package com.itclass.auth.config;

import com.itclass.auth.authentication.provider.support.LdapAuthenticationProvider;
import com.itclass.auth.encoder.SimplPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.ldap.LdapBindAuthenticationManagerFactory;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
public class LdapConfig {

  @Bean
  public LdapAuthenticationProvider ldapAuthenticationProvider(BaseLdapPathContextSource baseLdapPathContextSource,DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator) {

    BindAuthenticator bindAuthenticator = new BindAuthenticator(baseLdapPathContextSource);
    bindAuthenticator.setUserDnPatterns(new String[]{"cn={0},ou=users"});
    bindAuthenticator.afterPropertiesSet();
    LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator,
           defaultLdapAuthoritiesPopulator);
    return ldapAuthenticationProvider;
  }

  @Bean
  public DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator(BaseLdapPathContextSource contextSource) {
    String groupSearchBase = "ou=groups";
    DefaultLdapAuthoritiesPopulator authorities = new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase);
    authorities.setSearchSubtree(true);
    return authorities;
  }
}